import userCenterDelAccountApi from '@/api/userCenter/userCenterDelAccountApi'
import IUserCenterDelAccountForm from '@/model/form/userCenter/IUserCenterDelAccountForm'
import { useAppSelector } from '@/store'
import { passwordRSAEncrypt } from '@/util/UserUtil'
import Validator from '@/util/Validator'
import { Form, Modal } from '@douyinfe/semi-ui'
import { FormApi } from '@douyinfe/semi-ui/lib/es/form'
import { Dispatch, SetStateAction, useRef, useState } from 'react'
import { text } from 'stream/consumers'

interface IDelAccount {
  modalVisible: boolean
  setModalVisible: Dispatch<SetStateAction<boolean>>
}

export default function DelAccount(props: IDelAccount) {
  const formApi = useRef<FormApi>()
  const [confirmLoading, setConfirmLoading] = useState(false) // modal确认按钮的 loading状态
  const rsaPublicKey = useAppSelector((state) => state.common.rsaPublicKey)

  return (
    <Modal
      title="账号注销"
      visible={props.modalVisible}
      onOk={() => {
        formApi.current?.submitForm()
      }}
      onCancel={() => {
        props.setModalVisible(false)
      }}
      maskClosable={false}
      confirmLoading={confirmLoading}
    >
      <Form
        onSubmit={(form) => {
          if (confirmLoading) return
          modalSubmitClick(
            form as IUserCenterDelAccountForm,
            setConfirmLoading,
            rsaPublicKey
          )
        }}
        getFormApi={(api) => (formApi.current = api)}
        disabled={confirmLoading}
      >
        <Form.Input
          label={{ text: '验证账号密码', required: true }}
          field="password"
          validate={Validator['passwordValidate']}
          showClear
          mode="password"
        />
      </Form>
    </Modal>
  )
}

// 表单提交
function modalSubmitClick(
  form: IUserCenterDelAccountForm,
  setConfirmLoading: Dispatch<SetStateAction<boolean>>,
  rsaPublicKey: string
) {
  setConfirmLoading(true)

  form.password = passwordRSAEncrypt(form.password, rsaPublicKey)

  // 这里不用管，socket 收到消息后，跳转页面时会自动关闭 modal
  userCenterDelAccountApi(form).catch(() => {
    setConfirmLoading(false)
  })
}
